﻿using Consul;
using Microsoft.Extensions.Options;

namespace ELF;

public class ConsulService : IConsulService
{
    private readonly IConsulClient _consulClient;
    private readonly ConsulOptions _options;

    public ConsulService(IConsulClient consulClient, IOptions<ConsulOptions> options)
    {
        _options = options.Value;
        _consulClient = _consulClient ?? new ConsulClient(config => config.Address = new Uri(_options.Address));
    }

    // 获取服务的所有健康实例
    public async Task<List<ServiceEntry>> GetServiceAsync(string serviceName)
    {
        var queryResult = await _consulClient.Health.Service(
            service: serviceName,
            tag: "",          // 可选: 过滤服务标签
            passingOnly: true // 只返回健康实例
        );

        return queryResult.Response.ToList();
    }

    public async Task<Uri> GetServiceUriAsync(string serviceName)
    {
        // 随机选择一个健康实例（简单负载均衡）
        var services = await GetServiceAsync(serviceName);
        if (services.Count == 0)
            throw new Exception("No healthy authentication service instances found");

        var serviceEntry = services[new Random().Next(services.Count)];

        // 构造服务地址（考虑处理IPv6地址）
        var host = string.IsNullOrEmpty(serviceEntry.Service.Address)
            ? serviceEntry.Service.Service
            : serviceEntry.Service.Address;

        return new Uri($"http://{host}:{serviceEntry.Service.Port}/");
    }
}
